// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
//
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.warehouse.viewers.excel;

import static org.dengues.core.IDesignerCoreService.EXCEL_FIRSTCOLUMN;
import static org.dengues.core.IDesignerCoreService.EXCEL_FIRSTROW;
import static org.dengues.core.IDesignerCoreService.EXCEL_HEADER;
import static org.dengues.core.IDesignerCoreService.EXCEL_LASTCOLUMN;
import static org.dengues.core.IDesignerCoreService.EXCEL_LASTROW;
import static org.dengues.core.IDesignerCoreService.EXCEL_SHEET;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dengues.core.DenguesCorePlugin;
import org.dengues.core.components.IXMLComponent;
import org.dengues.core.warehouse.ENodeCategoryName;
import org.dengues.model.database.DatabaseDiagram;
import org.dengues.warehouse.viewers.wizards.NewElementWizardPage3;
import org.eclipse.core.runtime.IPath;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf Qiang.Zhang.Adolf@gmail.com 2008-7-4 qiang.zhang $
 * 
 */
public class NewExcelWizardPage3 extends NewElementWizardPage3 {

    private Combo sheetText;

    private Text headertext;

    private Text fColtext;

    private Text lColtext;

    private Text fRowtext;

    private Text lRowtext;

    private String[] fieds;

    /**
     * Qiang.Zhang.Adolf@gmail.com NewCSVWizardPage3 constructor comment.
     * 
     * @param path
     * @param database
     */
    public NewExcelWizardPage3(IPath path, DatabaseDiagram database, ENodeCategoryName name) {
        super(path, database, name);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.warehouse.viewers.wizards.NewElementWizardPage3#createMiddleContent(org.eclipse.swt.widgets.Composite)
     */
    @Override
    protected void createMiddleContent(Composite container) {
        Composite composite = new Composite(container, SWT.NONE);
        GridLayout gridLayout = new GridLayout(6, false);
        composite.setLayout(gridLayout);
        Label label = new Label(composite, SWT.NONE);
        label.setText("Sheet Name:");
        sheetText = new Combo(composite, SWT.BORDER);
        GridData gridData = new GridData();
        gridData.widthHint = 105;
        sheetText.setLayoutData(gridData);
        if (database != null) {
            sheetText.setText((String) database.getProperties().get(EXCEL_SHEET));
        } else {
            sheetText.setText("");
        }

        label = new Label(composite, SWT.NONE);
        label.setText("Header:");
        headertext = new Text(composite, SWT.BORDER);
        gridData = new GridData();
        gridData.widthHint = 120;
        headertext.setLayoutData(gridData);
        if (database != null) {
            headertext.setText((String) database.getProperties().get(EXCEL_HEADER));
        } else {
            headertext.setText("0");
        }

        label = new Label(composite, SWT.NONE);
        label.setText("First Column:");
        fColtext = new Text(composite, SWT.BORDER);
        gridData = new GridData();
        gridData.widthHint = 120;
        fColtext.setLayoutData(gridData);
        if (database != null) {
            fColtext.setText((String) database.getProperties().get(EXCEL_FIRSTCOLUMN));
        } else {
            fColtext.setText("1");
        }

        label = new Label(composite, SWT.NONE);
        label.setText("Last Column:");
        lColtext = new Text(composite, SWT.BORDER);
        gridData = new GridData();
        gridData.widthHint = 120;
        lColtext.setLayoutData(gridData);
        if (database != null) {
            lColtext.setText((String) database.getProperties().get(EXCEL_LASTCOLUMN));
        } else {
            lColtext.setText("1");
        }

        label = new Label(composite, SWT.NONE);
        label.setText("First Row:");
        fRowtext = new Text(composite, SWT.BORDER);
        gridData = new GridData();
        gridData.widthHint = 120;
        fRowtext.setLayoutData(gridData);
        if (database != null) {
            fRowtext.setText((String) database.getProperties().get(EXCEL_FIRSTROW));
        } else {
            fRowtext.setText("1");
        }

        label = new Label(composite, SWT.NONE);
        label.setText("Last Row:");
        lRowtext = new Text(composite, SWT.BORDER);
        gridData = new GridData();
        gridData.widthHint = 120;
        lRowtext.setLayoutData(gridData);
        if (database != null) {
            lRowtext.setText((String) database.getProperties().get(EXCEL_LASTROW));
        } else {
            lRowtext.setText("2");
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.warehouse.viewers.wizards.NewElementWizardPage3#getProperties()
     */
    @Override
    public HashMap<String, Object> getProperties() {
        HashMap<String, Object> properties = super.getProperties();
        properties.put(EXCEL_SHEET, sheetText.getText());
        properties.put(EXCEL_HEADER, headertext.getText());
        properties.put(EXCEL_FIRSTCOLUMN, fColtext.getText());
        properties.put(EXCEL_FIRSTROW, fRowtext.getText());
        properties.put(EXCEL_LASTCOLUMN, lColtext.getText());
        properties.put(EXCEL_LASTROW, lRowtext.getText());
        return properties;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getFields".
     * 
     * @return
     */
    private List<Map<String, Object>> getFields() {
        List<Map<String, Object>> mapping = new ArrayList<Map<String, Object>>();
        int i = 0;
        for (String map : fieds) {
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put(IXMLComponent.COLUMN_SCHEMA, "row" + i); //$NON-NLS-1$
            map2.put(QUERY, map);
            mapping.add(map2);
            i++;
        }
        return mapping;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean)
     */
    @Override
    public void setVisible(boolean visible) {
        super.setVisible(visible);
        if (visible) {
            CTabFolder folder = ((NewExcelWizardPage2) getPreviousPage()).getFolder();
            String[] ss = new String[folder.getItemCount()];
            for (int i = 0; i < ss.length; i++) {
                ss[i] = folder.getItems()[i].getText();
            }
            sheetText.setItems(ss);
            CTabItem selection = folder.getSelection();
            if (selection != null) {
                sheetText.setText(selection.getText());
                Table control2 = (Table) selection.getControl();
                lColtext.setText("" + (control2).getColumnCount());
                fColtext.setText("0");
                TableItem[] selection2 = control2.getSelection();
                TableItem item = null;
                if (selection2 == null || selection2.length == 0) {
                    if (control2.getItemCount() > 0) {
                        item = control2.getItem(Integer.parseInt(headertext.getText()));
                    }
                } else {
                    item = selection2[0];
                }
                int columnCount = control2.getColumnCount();
                fieds = new String[columnCount];
                for (int i = 0; i < columnCount; i++) {
                    fieds[i] = item.getText(i);
                }
            }
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.warehouse.viewers.wizards.NewElementWizardPage3#addListeners()
     */
    @Override
    protected void addListeners() {
        guessBtn.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            public void widgetSelected(SelectionEvent e) {
                List<String[]> csvRows = DenguesCorePlugin.getDefault().getDesignerCoreService().getExcelPreviewRows(
                        getProperties(), getFields());
                retieveSchema(csvRows, getFields());
            }
        });
    }
}
